<template>
  <div class="employees">
    <el-card style="text-align: right">
      <div>
        <el-button
          type="primary"
          size="small"
          @click="$router.push('/employees/import')"
        >导入</el-button>
        <el-button
          type="primary"
          size="small"
          @click="excelOut"
        >导出</el-button>
        <el-button
          type="primary"
          size="small"
          @click="add"
        >+ 新增员工</el-button>
      </div>
    </el-card>
    <el-card style="margin-top: 15px">
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column width="50" label="序号">
          <template v-slot="{ $index }">
            <div>
              {{ (page.page - 1) * page.size + $index + 1 }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="姓名" prop="username" sortable />
        <el-table-column label="用户头像" sortable>
          <template v-slot="{ row }">
            <div>
              <img
                v-errorimg
                class="img"
                :src="row.staffPhoto"
                alt=""
                @click="qrcodeClick(row.staffPhoto)"
              >
            </div>
          </template>
        </el-table-column>
        <el-table-column label="手机号" prop="mobile" sortable />
        <el-table-column label="工号" prop="workNumber" sortable />
        <el-table-column label="聘用形势" prop="formOfEmployment" sortable>
          <template v-slot="{ row }">
            <div>
              {{ row.formOfEmployment | formEmployment }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="部门" prop="departmentName" sortable />
        <el-table-column label="入职时间" prop="timeOfEntry" sortable>
          <template v-slot="{ row }">
            <div v-formatTime="row.timeOfEntry" />
          </template>
        </el-table-column>
        <el-table-column label="是否在职" prop="enableState" sortable>
          <template v-slot="{ row }">
            <div>
              {{ row.enableState | workingState }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300px">
          <template v-slot="{ row }">
            <div>
              <el-button type="text" @click="userLook(row.id)">查看</el-button>
              <el-button type="text">转正</el-button>
              <el-button type="text">调岗</el-button>
              <el-button type="text">离职</el-button>
              <el-button
                type="text"
                @click="rolesClick(row.id)"
              >角色</el-button>
              <el-button type="text" @click="del(row.id)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div style="text-align: right; margin-top: 15px">
        <el-pagination
          :page-sizes="[1, 5, 10, 20, 30, 40]"
          :page-size="page.size"
          :total="page.total"
          :current-page="page.page"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
      <!-- 新增 -->
      <add ref="addItem" @getData="getData" />
      <!-- 二维码生成弹框 -->
      <el-dialog
        title="二维码生成"
        width="600px"
        :visible.sync="qrcodeShow"
        style="text-align: center"
      >
        <canvas ref="canvas" />
      </el-dialog>
      <!-- 角色弹框组件 -->
      <Roles ref="roles" />
    </el-card>
  </div>
</template>

<script>
import { sysUser, sysRoleDelete } from '@/api/employees'
import jsCookie from 'js-cookie'
import filterList from '@/api/constant/employees'
import add from './components/add.vue'
import { export_json_to_excel } from '@/vendor/Export2Excel'
import moment from 'moment'
import Qrcode from 'qrcode' // 导入二维码生成器
import Roles from './components/Roles.vue'
export default {
  components: {
    add,
    Roles
  },
  filters: {
    formEmployment(id) {
      const result = filterList.hireType.find((item) => +item.id === +id)
      return result ? result.value : '-'
    },
    workingState(id) {
      const result = filterList.workingState.find((item) => +item.id === +id)
      return result ? result.value : '-'
    }
  },
  data() {
    return {
      qrcodeShow: false, // 二维码开关
      tableData: [],
      page: {
        page: 1, // 页码
        size: +jsCookie.get('employess-size') || 1, // 页容量
        total: 10 // 总数
      }
    }
  },
  created() {
    this.getData()
  },
  methods: {
    // 每页多少条数据 也容量
    handleSizeChange(size) {
      this.page.size = size
      jsCookie.set('employess-size', size)
      this.getData()
    },
    // 当前第几页 页码改变时触发
    handleCurrentChange(page) {
      this.page.page = page
      // console.log(this.tableData)
      this.getData()
    },
    // 获取员工列表信息
    async getData() {
      const res = await sysUser(this.page)
      // console.log('员工列表信息', res)
      this.page.total = res.data.total
      this.tableData = res.data.rows
    },
    // 新增弹框组件
    add() {
      this.$refs.addItem.isShow = true
    },
    // 删除角色
    del(id) {
      this.$confirm('是否删除该员工', '提示', {
        type: 'warning'
      }).then(async() => {
        await sysRoleDelete(id)
        this.$message.success('删除员工成功')
        // 页码大于1 且中有一个数据时
        if (this.page.page > 1 && this.tableData.length <= 1) {
          this.page.page--
        }
        this.getData()
      })
    },
    // 导出excel表格
    async excelOut() {
      // 1.获取所有员工数据
      const res = await sysUser({
        page: 1,
        size: 99999
      })
      // 2.定制导出规则
      const rules = {
        姓名: 'username',
        手机号: 'mobile',
        工号: 'workNumber',
        聘用形式: 'formOfEmployment',
        部门: 'departmentName',
        入职时间: 'timeOfEntry',
        转正时间: 'correctionTime',
        是否在职: 'enableState'
      }
      // 3.调用方法
      // 4.excel中data是多层数据结构 需要转换 变成双数组结构
      // 5.遍历获取的所有员工数据 进行数据转化
      const newArr = res.data.rows.map((item) => {
        const arr = []
        // console.log(item)
        Object.values(rules).forEach((i) => {
          if (i === 'timeOfEntry' || i === 'correctionTime') {
            arr.push(moment(item[i]).format('YYYY-DD-SS'))
          } else if (i === 'formOfEmployment') {
            // 1.循环遍历数组 找到id相同项 id相同的添加到数组里
            const res = filterList.hireType.find(
              (item2) => +item[i] === +item2.id
            )
            // if (res) {
            //   arr.push(res.value)
            // } else {
            //   arr.push('-')
            // }
            res ? arr.push(res.value) : arr.push('-')
          } else if (i === 'enableState') {
            const res = filterList.workingState.find(
              (item3) => +item[i] === +item3.id
            )
            // if (res) {
            //   arr.push(res.value)
            // } else {
            //   arr.push('-')
            // }
            res ? arr.push(res.value) : arr.push('-')
          } else {
            arr.push(item[i])
          }
        })
        return arr
      })
      // console.log(newArr)
      export_json_to_excel({
        header: Object.keys(rules),
        data: newArr,
        filename: '导出员工列表'
      })
    },
    // 点击查看跳转页面
    userLook(id) {
      this.$router.push('/employees/userlook/' + id)
    },
    // 二维码生成开关
    qrcodeClick(row) {
      if (row && row.trim()) {
        this.qrcodeShow = true
        this.$nextTick(() => {
          Qrcode.toCanvas(this.$refs.canvas, row, {
            width: 300,
            height: 300
          })
        })
      }
    },
    // 角色弹框打开
    rolesClick(id) {
      this.$refs.roles.showRoles = true
      this.$refs.roles.getList(id)
    }
  }
}
</script>

<style lang="scss" scoped>
.employees {
  padding: 15px;
  .img {
    width: 30px;
    height: 30px;
  }
}
</style>
